package com.yhos.platform.oopston.core.logback;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.yhos.platform.oopston.core.manager.TraceConstant;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.Map;
import java.util.UUID;

/**
 * 新增日志链路格式转换器
 * 将Header请求参数写入日志，便于后续跟踪和分析
 */
public class TraceConverter extends ClassicConverter {

    private static final String DEFAULT_EMPTY = "N/A";

    private String traceLogFormat = "[TraceId#{0}][ServerIP#{1}][Source#{2}][FromSource#{3}][Token#{4}][Platform#{5}][Version#{6}]";

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        Map<String, String> contextMap = iLoggingEvent.getMDCPropertyMap();
        if (contextMap != null && contextMap.size() > 0) {
            // 从Event的MDC中获取Header信息
            // 有上下文请求的情况下
            return MessageFormat.format(traceLogFormat,
                    StringUtils.defaultIfBlank(contextMap.get(TraceConstant.FROM_SOURCE_ID), DEFAULT_EMPTY),
                    StringUtils.defaultIfBlank(contextMap.get(TraceConstant.REQUEST_IP), DEFAULT_EMPTY),
                    StringUtils.defaultIfBlank(contextMap.get(TraceConstant.SOURCE), DEFAULT_EMPTY),
                    StringUtils.defaultIfBlank(contextMap.get(TraceConstant.FROM_SOURCE), DEFAULT_EMPTY),
                    StringUtils.defaultIfBlank(contextMap.get(TraceConstant.USER_TOKEN), DEFAULT_EMPTY),
                    StringUtils.defaultIfBlank(contextMap.get(TraceConstant.PLATFORM), DEFAULT_EMPTY),
                    StringUtils.defaultIfBlank(contextMap.get(TraceConstant.VERSION), DEFAULT_EMPTY));
        } else {
            // 极端情况下即取不到请求上下文，也没有默认值得情况下，特殊处理，可能存在不会没有考虑到的场景
            return MessageFormat.format(traceLogFormat,
                    UUID.randomUUID().toString(),
                    null,
                    DEFAULT_EMPTY,
                    DEFAULT_EMPTY,
                    DEFAULT_EMPTY,
                    DEFAULT_EMPTY,
                    DEFAULT_EMPTY);
        }
    }

}
